{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 使用随机森林实现波士顿房价预测及可视化",
   "id": "cd57b34a2252f914"
  },
  {
   "metadata": {
    "collapsed": true
   },
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "from sklearn.preprocessing import StandardScaler"
   ],
   "id": "initial_id"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "波士顿数据集的列顺序通常如下：\n",
    "| 列名  | 全称/含义                          | 单位/范围                  | 对房价的影响方向 | 备注                          |\n",
    "|-------|-----------------------------------|---------------------------|------------------|-------------------------------|\n",
    "| **CRIM** | 城镇人均犯罪率                     | 比例值（通常按每万居民）   | ↓ 负相关         | 犯罪率越高，房价越低           |\n",
    "| **ZN**   | 大型住宅用地比例（>25k平方英尺）  | 百分比（0-100）           | ↑ 正相关         | 高密度住宅区可能更贵           |\n",
    "| **INDUS**| 非零售商业用地比例                 | 百分比（0-100）           | ↓ 负相关         | 工业区附近房价通常较低         |\n",
    "| **CHAS** | 是否临查尔斯河                     | 0或1（二元变量）          | ↑ 正相关         | 1=临河，0=不临河              |\n",
    "| **NOX**  | 氮氧化物浓度（空气质量）           | ppm（百万分之一）          | ↓ 负相关         | 污染越重，房价越低             |\n",
    "| **RM**   | 住宅平均房间数                     | 数值（通常3-9）            | ↑ 正相关         | 房间越多，房价越高             |\n",
    "| **AGE**  | 1940年前建成的老旧房屋比例         | 百分比（0-100）           | ↓ 负相关         | 老旧房屋比例高则房价低         |\n",
    "| **DIS**  | 到就业中心的加权距离               | 标准化距离值               | ↓ 负相关         | 距离越近，房价越高             |\n",
    "| **RAD**  | 高速公路可达性指数                 | 分类值（1-24）            | ↑ 正相关         | 交通便利性影响房价             |\n",
    "| **TAX**  | 每10万美元房产税率                 | 美元                       | ↓ 负相关         | 高税率可能抑制房价             |\n",
    "| **PTRATIO**| 学生/教师比例                     | 数值（如12-22）           | ↓ 负相关         | 比例越低（教育资源好）房价越高 |\n",
    "| **B**    | 黑人比例（1000×(Bk-0.63)²）      | 比例值                     | -                | 涉及敏感统计，谨慎使用         |\n",
    "| **LSTAT**| 低收入人群比例                     | 百分比（0-100）           | ↓ 负相关         | 低收入比例高则房价低           |\n",
    "| **MEDV** | 房价中位数（目标变量）             | 千美元（1970年代）         | -                | 需要预测的变量                 |\n"
   ],
   "id": "2605e1aab9516684"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 定义列名（根据波士顿房价数据集的描述）\n",
    "column_names = [\n",
    "    'CRIM',  # 城镇人均犯罪率\n",
    "    'ZN',  # 住宅用地比例\n",
    "    'INDUS',  # 非零售商业用地比例\n",
    "    'CHAS',  # 是否靠近查尔斯河(1=是，0=否)\n",
    "    'NOX',  # 氮氧化物浓度\n",
    "    'RM',  # 住宅平均房间数\n",
    "    'AGE',  # 1940年前建成的自住房屋比例\n",
    "    'DIS',  # 到波士顿五个就业中心的加权距离\n",
    "    'RAD',  # 径向公路可达性指数\n",
    "    'TAX',  # 每万美元财产税率\n",
    "    'PTRATIO',  # 城镇师生比例\n",
    "    'B',  # 黑人比例\n",
    "    'LSTAT',  # 低收入人口比例\n",
    "    'MEDV'  # 自住房屋中位数价格(目标变量)\n",
    "]\n",
    "\n",
    "# 读取数据并指定列名\n",
    "data = pd.read_csv('../data/波士顿房价数据集/housing.data.txt',\n",
    "                   header=None,  # 确保不将第一行误认为表头\n",
    "                   sep='\\s+',  # 按空格/制表符分隔（波士顿数据集是空格分隔）\n",
    "                   names=column_names)  # 传入列名\n",
    "\n"
   ],
   "id": "9b281c97e2fb376c",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# data.describe()\n",
    "data.info()"
   ],
   "id": "b2d567f0fa04a8b1",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 分离特征和目标变量\n",
    "X = data.drop('MEDV', axis=1)\n",
    "y = data['MEDV']"
   ],
   "id": "c76536da75dd2aae",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 数据标准化\n",
    "scaler = StandardScaler()\n",
    "X_scaled = scaler.fit_transform(X)"
   ],
   "id": "8ec3d4555fc70e81",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 划分训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)"
   ],
   "id": "59da90f62baaf52c",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 创建线性回归模型\n",
    "model = LinearRegression()"
   ],
   "id": "2eace8afc67ced4f",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 训练模型\n",
    "model.fit(X_train, y_train)"
   ],
   "id": "c9f38b7e23029fe3",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 在训练集上预测\n",
    "y_train_pred = model.predict(X_train)\n",
    "\n",
    "# 在测试集上预测\n",
    "y_test_pred = model.predict(X_test)"
   ],
   "id": "b0f6fc6684e8d30d",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-08T13:49:20.913941Z",
     "start_time": "2025-08-08T13:49:20.905849Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 评估模型\n",
    "print('\\n模型评估:')\n",
    "print('训练集R²分数:', r2_score(y_train, y_train_pred))\n",
    "print('测试集R²分数:', r2_score(y_test, y_test_pred))\n",
    "print('训练集均方误差:', mean_squared_error(y_train, y_train_pred))\n",
    "print('测试集均方误差:', mean_squared_error(y_test, y_test_pred))"
   ],
   "id": "b934963c5ec14225",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "模型评估:\n",
      "训练集R²分数: 0.7508856358979673\n",
      "测试集R²分数: 0.668759493535632\n",
      "训练集均方误差: 21.641412753226312\n",
      "测试集均方误差: 24.29111947497352\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "id": "311cb5006ee575e",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "id": "bf63466109775439",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "id": "1d622e8ba0af0a01",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "id": "a22c73960a5e3369",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
